package global

import (
	"context"
	"encoding/json"
	"strings"
	"time"

	kitJwt "github.com/go-kit/kit/auth/jwt"
	"github.com/golang-jwt/jwt/v4"
	"github.com/sirupsen/logrus"
)

// 需要在 jwt 中来回传递的数据
type Claims struct {
	UID      int64  `json:"uid"`
	UserName string `json:"username"`
	Ts       int64  `json:"ts"`
	jwt.StandardClaims
}

// 获取jwt解析token获取到的参数
func GetParam(ctx context.Context) map[string]interface{} {
	t1 := ctx.Value(kitJwt.JWTClaimsContextKey)
	if t1 == nil {
		return nil
	}
	value := t1.(jwt.MapClaims)
	marshal, _ := json.Marshal(value)
	logrus.Info("Token 解析到的参数：", string(marshal))
	return value
}

// 获取jwt解析token获取到的参数 true-可通行，false-token校验不通过
func GetParam2(token string) (*Claims, bool) {
	if strings.Compare(token, "") == 0 {
		return nil, false
	}
	// 解密token
	jwtClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) { /*返回一个token类型指针*/
		return []byte("test_signing_key"), nil
	})
	if err != nil || jwtClaims == nil {
		return nil, false
	}
	claims, ok := jwtClaims.Claims.(*Claims)
	if !ok && !jwtClaims.Valid {
		return nil, false
	}
	return claims, true
}

// 生成token
func GenToken(claims Claims) (string, error) {
	claims.Ts = time.Now().UnixNano()
	expired := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return expired.SignedString([]byte("test_signing_key"))
}
